package com.example.backend.security;


import com.example.backend.entitly.mysql.user.UserAuth;
import com.example.backend.service.mysql.permission.PermissionService;
import com.example.backend.service.mysql.user.UserAuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
@RequiredArgsConstructor
public class UsernameDetailsService implements UserDetailsService {

    private final UserAuthService userAuthService;
    private final PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAuth byUsername = userAuthService.getByUsername(username);
        if (byUsername == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Collection<SimpleGrantedAuthority> authorities = permissionService.getByAuthorities(byUsername.getUserId());
        return new SecurityUser(byUsername.getIdentifier(), byUsername.getCredential(), authorities, byUsername.getIsActive().equals(1), true, true, true, byUsername.getUserId());
    }
}
